@cachly-dev/mcp-server 0.10.249 → 0.10.251

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/autor.js CHANGED
@@ -1 +1 @@
1
- import{execFileSync as c}from"node:child_process";const m=e=>t=>{try{return t.startsWith("-")?"":c("git",["config",t],{cwd:e,encoding:"utf-8",stdio:"pipe",timeout:1500,windowsHide:!0}).trim()}catch{return""}};function r(e){const t=(e??"").trim();return t?(t.split(/[\s.]+/)[0]??"").toLowerCase().replace(/[^a-z0-9_-]/g,"").slice(0,32):""}const a=new Set(["-","anonym","anonymous","none","kein","off"]);function g(e){const t=(e.uebergeben??"").trim().toLowerCase();if(a.has(t))return{autor:"",quelle:"anonym"};const n=(e.umgebung??"").trim().toLowerCase();if(a.has(n))return{autor:"",quelle:"anonym"};const o=r(e.uebergeben??"");if(o)return{autor:o,quelle:"uebergeben"};const u=r(e.umgebung??"");if(u)return{autor:u,quelle:"umgebung"};const i=r(e.git("user.name"));if(i)return{autor:i,quelle:"git-name"};const l=e.git("user.email"),s=r((l??"").split("@")[0]??"");return s?{autor:s,quelle:"git-mail"}:{autor:"",quelle:"unbekannt"}}const h="coauthor";function b(e){const t=(e??"").trim().toLowerCase();return!t||t==="off"||t==="false"||t==="0"||t==="none"?"":r(t)}function p(e,t){return e?!t||t===e?e:`${e}+${t}`:""}function d(e){return(e??"").split("+")[0]??""}function w(e){return e.autor||e.quelle==="anonym"?null:'\u{1F464} **No author found** \u2014 neither `author`, nor `CACHLY_AUTHOR`, nor `git config user.name`. Without an author this lesson does not count as team knowledge: `brain_who_knows` finds nobody and reuse across people stays uncounted. A `git config user.name "Your Name"` in the project is enough for all future lessons.'}export{h as COAUTHOR_PREF_KEY,w as autorHinweis,b as coautorAus,m as echterGitLeser,g as ermittleAutor,p as mitCoautor,r as normalisiere,d as nurMensch};
1
+ import{execFileSync as f}from"node:child_process";const w=e=>t=>{try{return t.startsWith("-")?"":f("git",["config",t],{cwd:e,encoding:"utf-8",stdio:"pipe",timeout:1500,windowsHide:!0}).trim()}catch{return""}};function r(e){const t=(e??"").trim();return t?(t.split(/[\s.]+/)[0]??"").toLowerCase().replace(/[^a-z0-9_-]/g,"").slice(0,32):""}const l=new Set(["-","anonym","anonymous","none","kein","off"]);function b(e){const t=(e.uebergeben??"").trim().toLowerCase();if(l.has(t))return{autor:"",quelle:"anonym"};const o=(e.umgebung??"").trim().toLowerCase();if(l.has(o))return{autor:"",quelle:"anonym"};const u=r(e.uebergeben??"");if(u)return{autor:u,quelle:"uebergeben"};const i=r(e.umgebung??"");if(i)return{autor:i,quelle:"umgebung"};const s=r(e.git("user.name"));if(s)return{autor:s,quelle:"git-name"};const c=e.git("user.email"),a=r((c??"").split("@")[0]??"");return a?{autor:a,quelle:"git-mail"}:{autor:"",quelle:"unbekannt"}}const p="coauthor";function h(e){const t=(e??"").trim().toLowerCase();return!t||t==="off"||t==="false"||t==="0"||t==="none"?"":r(t)}function x(e,t){return e?!t||t===e?e:`${e}+${t}`:""}function q(e){return(e??"").split("+")[0]??""}function m(e){return e.autor||e.quelle==="anonym"?null:'\u{1F464} **Tip:** saved without an author name. Set `git config user.name "Your Name"` (or `CACHLY_AUTHOR`) once, and `brain_who_knows` can tell teammates who knows this.'}let n=!1;function A(e){const t=m(e);return!t||n?null:(n=!0,t)}function C(){n=!1}export{p as COAUTHOR_PREF_KEY,m as autorHinweis,A as autorHinweisEinmal,h as coautorAus,w as echterGitLeser,b as ermittleAutor,x as mitCoautor,r as normalisiere,q as nurMensch,C as setzeAutorHinweisZurueck};
@@ -1 +1 @@
1
- import{Seltenheit as f,inhaltsWoerter as c,grobStamm as p,spreizeImTopf as d}from"./rangfolge.js";import{lektionsText as w}from"./seltenheitsbestand.js";import{bestandAusDokumenten as g,keywordSearchMitBestand as k}from"./search.js";import{SINN_TOPF as E,EINBLENDUNG_DECKUNG as b,EINBLENDUNG_ZEUGE as N}from"./rangfolge-stellschrauben.js";import{istMarkiert as S}from"./verdacht-marke.js";import{rahmeEin as U,entschaerfe as j,RAHMEN_ETIKETT as B,RAHMEN_HINWEIS as P}from"./einblendung-rahmen.js";import{stopAntwort as F}from"./schreibbeleg.js";const x=E,_=["topic","outcome","what_worked","what_failed","severity","confidence","recall_count","ts","endorsements"],m=new Set("the a an and or but for to of in on at is are be do does did we you i it this that with without how what why when where can could would should please just get set use using make made need bitte und oder der die das ein eine f\xFCr mit ohne wie was warum kann soll noch mal auch von den dem ist weil wenn dann doch aber alle jede jeder jedes immer wieder wird werden wurde muss beim sehr nicht".split(/\s+/)),T=["ierungen","ierung","ieren","iert","ungen","ung","heit","keit","lich","isch","ing","ed","en","er","es","e","n","s"];function z(s){for(const e of T)if(s.length-e.length>=4&&s.endsWith(e))return s.slice(0,-e.length);return s}function y(s){return[...new Set(String(s).toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>3&&!m.has(e)).map(z).filter(e=>!m.has(e)))]}function I(s,e){let i=0;for(const o of s)e.includes(o)&&i++;return i}class A{texte;wortmengen;heuhaufen;statistik;wortbestand;platzVonSchluessel=new Map;topf;lektionen;constructor(e,{topf:i=x}={}){const o=e.filter(n=>!S(n));this.lektionen=o,this.topf=i,this.texte=o.map(n=>w(n)),this.wortmengen=this.texte.map(n=>new Set([...c(n)].map(p))),this.heuhaufen=this.texte.map(n=>n.toLowerCase()),this.statistik=new f(this.texte);const h=o.map((n,a)=>{const l=`cachly:lesson:best:${String(n.topic??a)}`;this.platzVonSchluessel.set(l,a);const u={};for(const t of _)n[t]!==void 0&&(u[t]=n[t]);return{key:l,content:JSON.stringify(u)}});this.wortbestand=g(h)}get groesse(){return this.lektionen.length}sortiere(e){if(!this.wortbestand)return[];const i=k(this.wortbestand,e,this.topf),o=[],h=[];for(const t of i){const r=this.platzVonSchluessel.get(t.key);r!==void 0&&(o.push(r),h.push(t.score))}if(o.length===0)return[];const n=c(e),a=y(e),l=d(h),u=d(o.map(t=>this.statistik.besterZeuge(n,this.wortmengen[t])));return o.map((t,r)=>({lektion:this.lektionen[t],punkte:l[r]+b*this.statistik.deckung(n,this.wortmengen[t])+N*u[r],belege:I(a,this.heuhaufen[t])})).sort((t,r)=>r.punkte-t.punkte||Number(r.lektion.recall_count??0)-Number(t.lektion.recall_count??0))}}export{A as Einblendbestand,_ as INDEX_FELDER,B as RAHMEN_ETIKETT,P as RAHMEN_HINWEIS,x as WORT_TOPF,j as entschaerfe,U as rahmeEin,z as stammKuerzen,F as stopAntwort,y as torWoerter,I as zaehleBelege};
1
+ import{Seltenheit as f,inhaltsWoerter as c,grobStamm as p,spreizeImTopf as m}from"./rangfolge.js";import{lektionsText as w}from"./seltenheitsbestand.js";import{bestandAusDokumenten as g,keywordSearchMitBestand as k}from"./search.js";import{SINN_TOPF as E,EINBLENDUNG_DECKUNG as b,EINBLENDUNG_ZEUGE as N}from"./rangfolge-stellschrauben.js";import{istMarkiert as S}from"./verdacht-marke.js";import{istTeamweit as x}from"./utils.js";import{rahmeEin as B,entschaerfe as P,RAHMEN_ETIKETT as C,RAHMEN_HINWEIS as F}from"./einblendung-rahmen.js";import{stopAntwort as K}from"./schreibbeleg.js";const _=E,T=["topic","outcome","what_worked","what_failed","severity","confidence","recall_count","ts","endorsements"],d=new Set("the a an and or but for to of in on at is are be do does did we you i it this that with without how what why when where can could would should please just get set use using make made need bitte und oder der die das ein eine f\xFCr mit ohne wie was warum kann soll noch mal auch von den dem ist weil wenn dann doch aber alle jede jeder jedes immer wieder wird werden wurde muss beim sehr nicht".split(/\s+/)),z=["ierungen","ierung","ieren","iert","ungen","ung","heit","keit","lich","isch","ing","ed","en","er","es","e","n","s"];function y(s){for(const e of z)if(s.length-e.length>=4&&s.endsWith(e))return s.slice(0,-e.length);return s}function I(s){return[...new Set(String(s).toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>3&&!d.has(e)).map(y).filter(e=>!d.has(e)))]}function D(s,e){let r=0;for(const o of s)e.includes(o)&&r++;return r}class L{texte;wortmengen;heuhaufen;statistik;wortbestand;platzVonSchluessel=new Map;topf;lektionen;constructor(e,{topf:r=_}={}){const o=e.filter(t=>!S(t)&&x(t));this.lektionen=o,this.topf=r,this.texte=o.map(t=>w(t)),this.wortmengen=this.texte.map(t=>new Set([...c(t)].map(p))),this.heuhaufen=this.texte.map(t=>t.toLowerCase()),this.statistik=new f(this.texte);const h=o.map((t,a)=>{const u=`cachly:lesson:best:${String(t.topic??a)}`;this.platzVonSchluessel.set(u,a);const l={};for(const n of T)t[n]!==void 0&&(l[n]=t[n]);return{key:u,content:JSON.stringify(l)}});this.wortbestand=g(h)}get groesse(){return this.lektionen.length}sortiere(e){if(!this.wortbestand)return[];const r=k(this.wortbestand,e,this.topf),o=[],h=[];for(const n of r){const i=this.platzVonSchluessel.get(n.key);i!==void 0&&(o.push(i),h.push(n.score))}if(o.length===0)return[];const t=c(e),a=I(e),u=m(h),l=m(o.map(n=>this.statistik.besterZeuge(t,this.wortmengen[n])));return o.map((n,i)=>({lektion:this.lektionen[n],punkte:u[i]+b*this.statistik.deckung(t,this.wortmengen[n])+N*l[i],belege:D(a,this.heuhaufen[n])})).sort((n,i)=>i.punkte-n.punkte||Number(i.lektion.recall_count??0)-Number(n.lektion.recall_count??0))}}export{L as Einblendbestand,T as INDEX_FELDER,C as RAHMEN_ETIKETT,F as RAHMEN_HINWEIS,_ as WORT_TOPF,P as entschaerfe,B as rahmeEin,y as stammKuerzen,K as stopAntwort,I as torWoerter,D as zaehleBelege};
@@ -1,8 +1,8 @@
1
- import{readFileSync as T,existsSync as C,writeFileSync as j,mkdirSync as F,statSync as W,appendFileSync as V}from"node:fs";import{dirname as R,join as _}from"node:path";import{tmpdir as b}from"node:os";import{createHash as X}from"node:crypto";import{spawn as Q}from"node:child_process";import{Einblendbestand as $,torWoerter as B}from"./einblendung-kern.js";import{rahmeEin as U,RAHMEN_HINWEIS as z}from"./einblendung-rahmen.js";import{istMarkiert as ee}from"./verdacht-marke.js";import{istBlossesThema as te}from"./blosses-thema.js";import{leserText as re}from"./seltenheitsbestand.js";import{mischeMitLeser as H}from"./leser.js";import{LeserSicherung as ne,dateiSpeicher as se,frageLeser as oe}from"./leser-sicherung.js";import{LESER_TIEFE_EINBLENDUNG as ie,LESER_ZEITLIMIT_MS as le}from"./rangfolge-stellschrauben.js";import{stufeEinblendungNachVersion as ae}from"./gueltigkeit-version.js";import{ARME as O,BASIS_MIN_BELEGE as ce,MERKMAL_KANDIDATEN as ue,OHNE_LERNEN as pe,entscheide as fe,leseArmZaehlung as he,lernEinstellungen as me,lernenAuffrischen as de,merkeEntscheidung as ge,neuerSatz as Ee,sitzungsKennung as _e,zugKennung as be}from"./lernen.js";export*from"./einblendung-kern.js";import{belohnungMelden as pt,lernenAuffrischen as ft,lernEinstellungen as ht,ARME as mt}from"./lernen.js";const Se=600*1e3,P=300*1e3,ye=10*1e3,Ae=2e3,Ne=50,Ie=60*1e3;function ve(e,t){return t<P?{ttlMs:ye,sofort:!0}:e<Ne?{ttlMs:Ie,sofort:!1}:{ttlMs:Se,sofort:!1}}const D=8e3,ke=60*1e3,J=120,K=ie,we=1500,I=le,Me=_(b(),"cachly-ambient-netlog.jsonl");function et(e=process.cwd()){const t={apiUrl:process.env.CACHLY_API_URL||"https://api.cachly.dev",jwt:process.env.CACHLY_JWT||"",instanceId:process.env.CACHLY_BRAIN_INSTANCE_ID||""};if(t.jwt&&t.instanceId)return t;let r=e;for(let n=0;n<8;n++){const s=_(r,".mcp.json");if(C(s))try{const i=JSON.parse(T(s,"utf8"))?.mcpServers?.cachly?.env??{};if(t.apiUrl=t.apiUrl||i.CACHLY_API_URL||"https://api.cachly.dev",t.jwt=t.jwt||i.CACHLY_JWT||"",t.instanceId=t.instanceId||i.CACHLY_BRAIN_INSTANCE_ID||"",t.jwt&&t.instanceId)return t}catch{}const o=R(r);if(o===r)break;r=o}return t}function v(e){return X("sha1").update(e).digest("hex").slice(0,12)}function q(e){return _(b(),`cachly-ambient-bestand-${v(e)}.json`)}function Le(e){return _(b(),`cachly-leser-sicherung-${v(e)}.json`)}function xe(e,t="ambient-auffrischen"){return _(b(),`cachly-${t}-${v(e)}.lock`)}async function k(e,{fetchFn:t=fetch,zeitlimitMs:r=D}={}){try{const n=await t(`${e.apiUrl}/api/v1/instances/${e.instanceId}/export`,{headers:{Authorization:`Bearer ${e.jwt}`},signal:AbortSignal.timeout(r)});if(!n.ok)return null;const s=await n.json();return!Array.isArray(s?.lessons)||s.lessons.length===0&&typeof s.note=="string"&&s.note?null:s.lessons.map(o=>typeof o=="string"?Te(o):o).filter(o=>!!o&&typeof o=="object")}catch{return null}}function Te(e){try{return JSON.parse(e)}catch{return null}}function S(e,t,r="server"){const n=Date.now(),s=y(e),o=s?.seit??n;let i;r==="vorab"?i=t:r==="server"&&s?.vorab&&n-o<P&&(i=s.vorab);const a=r==="server"&&i?Ce(t,i):t;try{F(R(e),{recursive:!0}),j(e,JSON.stringify({at:n,seit:o,lessons:a,...i?{vorab:i}:{}}),{mode:384})}catch{}return a}function Ce(e,t){const r=new Set(e.map(n=>n.topic));return[...e,...t.filter(n=>!r.has(n.topic))]}function tt(e,t){if(!e||t.length===0)return!1;const r=q(e);return(y(r)?.lessons.length??0)>0?!1:(S(r,t,"vorab"),!0)}function y(e){try{const t=JSON.parse(T(e,"utf8"));if(Array.isArray(t?.lessons)){const r=Number(t.at)||0;return{at:r,seit:Number(t.seit)||r,lessons:t.lessons,...Array.isArray(t.vorab)?{vorab:t.vorab}:{}}}}catch{}return null}function je(e,t,{zweck:r,ordner:n}={}){const s=xe(e.instanceId,r);try{if(C(s)&&Date.now()-W(s).mtimeMs<ke)return!1;j(s,String(Date.now()),{mode:384})}catch{return!1}try{return Q(process.execPath,t,{detached:!0,stdio:"ignore",...n?{cwd:n}:{},env:{...process.env,CACHLY_API_URL:e.apiUrl,CACHLY_JWT:e.jwt,CACHLY_BRAIN_INSTANCE_ID:e.instanceId}}).unref(),!0}catch{return!1}}async function Re(e,{force:t=!1,nebenlauf:r,abrufMs:n=D,lernen:s=!1,vorabSchliessen:o=!1,fetchFn:i}={}){if(!e.jwt||!e.instanceId)return{lessons:[],quelle:"nicht-eingerichtet"};const a=q(e.instanceId);if(t){const[m]=await Promise.all([k(e,{fetchFn:i,zeitlimitMs:n}),s?de(e,{fetchFn:i}):void 0]);if(m)return{lessons:S(a,m,o?"abschluss":"server"),quelle:"server"};const u=y(a);return u?{lessons:u.lessons,quelle:"platte-alt"}:{lessons:[],quelle:"server-nicht-erreichbar"}}const l=y(a);if(l){const m=Date.now(),u=ve(l.lessons.length,m-l.seit);if(m-l.at<u.ttlMs)return{lessons:l.lessons,quelle:"platte"};if(u.sofort){const h=await k(e,{fetchFn:i,zeitlimitMs:Math.min(n,Ae)});return h?{lessons:S(a,h),quelle:"server"}:{lessons:l.lessons,quelle:"platte-alt"}}return r&&je(e,r),{lessons:l.lessons,quelle:"platte-alt"}}const c=await k(e,{fetchFn:i,zeitlimitMs:n});return c?{lessons:S(a,c),quelle:"server"}:{lessons:[],quelle:"server-nicht-erreichbar"}}function w(e){return Math.ceil(String(e).length/4)}function M(e){const t=e.severity?`[${e.severity}] `:"",r=String(e.what_worked??"").replace(/\s+/g," ").trim(),n=r.length>J?`${r.slice(0,J)}\u2026`:r,s=typeof e.versionshinweis=="string"?` [${e.versionshinweis}]`:"";return`- ${t}${e.topic}${s}: ${n}`}const A={lessons:[],tokens:0,topScore:0,belege:0};function L(e,t,r){if(e.length===0)return{...A};const n=[];let s=0;e=ae(e);for(const{lektion:o}of e.slice(0,t)){const i=w(M(o));if(s+i>r)break;n.push(o),s+=i}return{lessons:n,tokens:s,topScore:Math.round(e[0].punkte*100)/100,belege:e[0].belege}}function rt(e,t,{minBelege:r=2,topK:n=3,tokenBudget:s=600}={}){if(!Array.isArray(t)||t.length===0)return{...A};if(B(e).length===0)return{...A};const o=new $(t).sortiere(e).filter(i=>i.belege>=r);return o.length===0?{...A}:L(o,n,s)}function $e(e){return re(e,we)}async function G(e,t,r,{zeitlimitMs:n=I,fetchFn:s}={}){if(!e?.jwt||!e?.instanceId||r.length===0)return{art:"ohne"};if(["0","off","aus","false"].includes(String(process.env.CACHLY_LESER||"").toLowerCase()))return{art:"ohne"};const o=new ne(se(Le(e.instanceId)));return oe({url:`${e.apiUrl}/api/v1/rerank`,jwt:e.jwt,frage:t,texte:r,instanceId:e.instanceId,zeitlimitMs:n,fetchFn:s},o)}async function nt(e,t,r,n={}){const s=await G(e,t,r,n);return s.art==="punkte"?{scores:s.scores,provider:s.provider,ms:s.ms}:null}async function Y(e,t,r,{minBelege:n,tiefe:s,zeitlimitMs:o,fetchFn:i}){const a={sortiert:[],leser:"aus",leserMs:0};if(!Array.isArray(t)||t.length===0||B(e).length===0)return a;let l=new $(t).sortiere(e).filter(u=>u.belege>=n);if(l.length===0)return a;let c="aus",m=0;if(l.length>1&&s>0){const u=l.slice(0,s),d=l.slice(s),h=await G(r,e,u.map(E=>$e(E.lektion)),{zeitlimitMs:o,fetchFn:i});h.art==="punkte"?(l=[...H(u.map(f=>f.punkte),h.scores,1).map(f=>({...u[f],leser:h.scores[f]})),...d],c=h.provider,m=h.ms):h.art==="uebersprungen"&&(c="uebersprungen")}return{sortiert:l,leser:c,leserMs:m}}async function st(e,t,r,{minBelege:n=2,topK:s=3,tokenBudget:o=600,tiefe:i=K,zeitlimitMs:a=I,fetchFn:l}={}){const c=await Y(e,t,r,{minBelege:n,tiefe:i,zeitlimitMs:a,fetchFn:l});return{...L(c.sortiert,s,o),leser:c.leser,leserMs:c.leserMs}}function Be(e){if(!e.lessons.length)return"";const t=e.lessons.map(M).join(`
1
+ import{readFileSync as T,existsSync as C,writeFileSync as j,mkdirSync as F,statSync as W,appendFileSync as V}from"node:fs";import{dirname as R,join as _}from"node:path";import{tmpdir as b}from"node:os";import{createHash as X}from"node:crypto";import{spawn as Q}from"node:child_process";import{Einblendbestand as $,torWoerter as B}from"./einblendung-kern.js";import{rahmeEin as U,RAHMEN_HINWEIS as z}from"./einblendung-rahmen.js";import{istMarkiert as ee}from"./verdacht-marke.js";import{istTeamweit as te}from"./utils.js";import{istBlossesThema as re}from"./blosses-thema.js";import{leserText as ne}from"./seltenheitsbestand.js";import{mischeMitLeser as H}from"./leser.js";import{LeserSicherung as se,dateiSpeicher as oe,frageLeser as ie}from"./leser-sicherung.js";import{LESER_TIEFE_EINBLENDUNG as le,LESER_ZEITLIMIT_MS as ae}from"./rangfolge-stellschrauben.js";import{stufeEinblendungNachVersion as ce}from"./gueltigkeit-version.js";import{ARME as O,BASIS_MIN_BELEGE as ue,MERKMAL_KANDIDATEN as pe,OHNE_LERNEN as fe,entscheide as he,leseArmZaehlung as me,lernEinstellungen as de,lernenAuffrischen as ge,merkeEntscheidung as Ee,neuerSatz as _e,sitzungsKennung as be,zugKennung as Se}from"./lernen.js";export*from"./einblendung-kern.js";import{belohnungMelden as ht,lernenAuffrischen as mt,lernEinstellungen as dt,ARME as gt}from"./lernen.js";const ye=600*1e3,P=300*1e3,Ae=10*1e3,Ne=2e3,Ie=50,ve=60*1e3;function ke(e,t){return t<P?{ttlMs:Ae,sofort:!0}:e<Ie?{ttlMs:ve,sofort:!1}:{ttlMs:ye,sofort:!1}}const D=8e3,we=60*1e3,J=120,K=le,Me=1500,I=ae,Le=_(b(),"cachly-ambient-netlog.jsonl");function rt(e=process.cwd()){const t={apiUrl:process.env.CACHLY_API_URL||"https://api.cachly.dev",jwt:process.env.CACHLY_JWT||"",instanceId:process.env.CACHLY_BRAIN_INSTANCE_ID||""};if(t.jwt&&t.instanceId)return t;let r=e;for(let n=0;n<8;n++){const s=_(r,".mcp.json");if(C(s))try{const i=JSON.parse(T(s,"utf8"))?.mcpServers?.cachly?.env??{};if(t.apiUrl=t.apiUrl||i.CACHLY_API_URL||"https://api.cachly.dev",t.jwt=t.jwt||i.CACHLY_JWT||"",t.instanceId=t.instanceId||i.CACHLY_BRAIN_INSTANCE_ID||"",t.jwt&&t.instanceId)return t}catch{}const o=R(r);if(o===r)break;r=o}return t}function v(e){return X("sha1").update(e).digest("hex").slice(0,12)}function q(e){return _(b(),`cachly-ambient-bestand-${v(e)}.json`)}function xe(e){return _(b(),`cachly-leser-sicherung-${v(e)}.json`)}function Te(e,t="ambient-auffrischen"){return _(b(),`cachly-${t}-${v(e)}.lock`)}async function k(e,{fetchFn:t=fetch,zeitlimitMs:r=D}={}){try{const n=await t(`${e.apiUrl}/api/v1/instances/${e.instanceId}/export`,{headers:{Authorization:`Bearer ${e.jwt}`},signal:AbortSignal.timeout(r)});if(!n.ok)return null;const s=await n.json();return!Array.isArray(s?.lessons)||s.lessons.length===0&&typeof s.note=="string"&&s.note?null:s.lessons.map(o=>typeof o=="string"?Ce(o):o).filter(o=>!!o&&typeof o=="object")}catch{return null}}function Ce(e){try{return JSON.parse(e)}catch{return null}}function S(e,t,r="server"){const n=Date.now(),s=y(e),o=s?.seit??n;let i;r==="vorab"?i=t:r==="server"&&s?.vorab&&n-o<P&&(i=s.vorab);const a=r==="server"&&i?je(t,i):t;try{F(R(e),{recursive:!0}),j(e,JSON.stringify({at:n,seit:o,lessons:a,...i?{vorab:i}:{}}),{mode:384})}catch{}return a}function je(e,t){const r=new Set(e.map(n=>n.topic));return[...e,...t.filter(n=>!r.has(n.topic))]}function nt(e,t){if(!e||t.length===0)return!1;const r=q(e);return(y(r)?.lessons.length??0)>0?!1:(S(r,t,"vorab"),!0)}function y(e){try{const t=JSON.parse(T(e,"utf8"));if(Array.isArray(t?.lessons)){const r=Number(t.at)||0;return{at:r,seit:Number(t.seit)||r,lessons:t.lessons,...Array.isArray(t.vorab)?{vorab:t.vorab}:{}}}}catch{}return null}function Re(e,t,{zweck:r,ordner:n}={}){const s=Te(e.instanceId,r);try{if(C(s)&&Date.now()-W(s).mtimeMs<we)return!1;j(s,String(Date.now()),{mode:384})}catch{return!1}try{return Q(process.execPath,t,{detached:!0,stdio:"ignore",...n?{cwd:n}:{},env:{...process.env,CACHLY_API_URL:e.apiUrl,CACHLY_JWT:e.jwt,CACHLY_BRAIN_INSTANCE_ID:e.instanceId}}).unref(),!0}catch{return!1}}async function $e(e,{force:t=!1,nebenlauf:r,abrufMs:n=D,lernen:s=!1,vorabSchliessen:o=!1,fetchFn:i}={}){if(!e.jwt||!e.instanceId)return{lessons:[],quelle:"nicht-eingerichtet"};const a=q(e.instanceId);if(t){const[m]=await Promise.all([k(e,{fetchFn:i,zeitlimitMs:n}),s?ge(e,{fetchFn:i}):void 0]);if(m)return{lessons:S(a,m,o?"abschluss":"server"),quelle:"server"};const u=y(a);return u?{lessons:u.lessons,quelle:"platte-alt"}:{lessons:[],quelle:"server-nicht-erreichbar"}}const l=y(a);if(l){const m=Date.now(),u=ke(l.lessons.length,m-l.seit);if(m-l.at<u.ttlMs)return{lessons:l.lessons,quelle:"platte"};if(u.sofort){const h=await k(e,{fetchFn:i,zeitlimitMs:Math.min(n,Ne)});return h?{lessons:S(a,h),quelle:"server"}:{lessons:l.lessons,quelle:"platte-alt"}}return r&&Re(e,r),{lessons:l.lessons,quelle:"platte-alt"}}const c=await k(e,{fetchFn:i,zeitlimitMs:n});return c?{lessons:S(a,c),quelle:"server"}:{lessons:[],quelle:"server-nicht-erreichbar"}}function w(e){return Math.ceil(String(e).length/4)}function M(e){const t=e.severity?`[${e.severity}] `:"",r=String(e.what_worked??"").replace(/\s+/g," ").trim(),n=r.length>J?`${r.slice(0,J)}\u2026`:r,s=typeof e.versionshinweis=="string"?` [${e.versionshinweis}]`:"";return`- ${t}${e.topic}${s}: ${n}`}const A={lessons:[],tokens:0,topScore:0,belege:0};function L(e,t,r){if(e.length===0)return{...A};const n=[];let s=0;e=ce(e);for(const{lektion:o}of e.slice(0,t)){const i=w(M(o));if(s+i>r)break;n.push(o),s+=i}return{lessons:n,tokens:s,topScore:Math.round(e[0].punkte*100)/100,belege:e[0].belege}}function st(e,t,{minBelege:r=2,topK:n=3,tokenBudget:s=600}={}){if(!Array.isArray(t)||t.length===0)return{...A};if(B(e).length===0)return{...A};const o=new $(t).sortiere(e).filter(i=>i.belege>=r);return o.length===0?{...A}:L(o,n,s)}function Be(e){return ne(e,Me)}async function G(e,t,r,{zeitlimitMs:n=I,fetchFn:s}={}){if(!e?.jwt||!e?.instanceId||r.length===0)return{art:"ohne"};if(["0","off","aus","false"].includes(String(process.env.CACHLY_LESER||"").toLowerCase()))return{art:"ohne"};const o=new se(oe(xe(e.instanceId)));return ie({url:`${e.apiUrl}/api/v1/rerank`,jwt:e.jwt,frage:t,texte:r,instanceId:e.instanceId,zeitlimitMs:n,fetchFn:s},o)}async function ot(e,t,r,n={}){const s=await G(e,t,r,n);return s.art==="punkte"?{scores:s.scores,provider:s.provider,ms:s.ms}:null}async function Y(e,t,r,{minBelege:n,tiefe:s,zeitlimitMs:o,fetchFn:i}){const a={sortiert:[],leser:"aus",leserMs:0};if(!Array.isArray(t)||t.length===0||B(e).length===0)return a;let l=new $(t).sortiere(e).filter(u=>u.belege>=n);if(l.length===0)return a;let c="aus",m=0;if(l.length>1&&s>0){const u=l.slice(0,s),d=l.slice(s),h=await G(r,e,u.map(E=>Be(E.lektion)),{zeitlimitMs:o,fetchFn:i});h.art==="punkte"?(l=[...H(u.map(f=>f.punkte),h.scores,1).map(f=>({...u[f],leser:h.scores[f]})),...d],c=h.provider,m=h.ms):h.art==="uebersprungen"&&(c="uebersprungen")}return{sortiert:l,leser:c,leserMs:m}}async function it(e,t,r,{minBelege:n=2,topK:s=3,tokenBudget:o=600,tiefe:i=K,zeitlimitMs:a=I,fetchFn:l}={}){const c=await Y(e,t,r,{minBelege:n,tiefe:i,zeitlimitMs:a,fetchFn:l});return{...L(c.sortiert,s,o),leser:c.leser,leserMs:c.leserMs}}function Ue(e){if(!e.lessons.length)return"";const t=e.lessons.map(M).join(`
2
2
  `);return`\u{1F9E0} Cachly Brain \u2014 relevant lessons for this task (auto-recall, ${e.lessons.length}):
3
3
  ${U(t)}
4
- (ambient-recall \xB7 ~${e.tokens} tokens \xB7 match score ${e.topScore})`}const Ue=5;function ot(e){const t=e.filter(l=>!ee(l));if(!t.length)return"";const r=t.filter(l=>{const c=String(l.topic??"");return!(/^auto:/.test(c)||te(c))}),n=[...r.length?r:t].sort((l,c)=>(Number(c.recall_count)||0)-(Number(l.recall_count)||0)).slice(0,Ue),s=n.map(M).join(`
4
+ (ambient-recall \xB7 ~${e.tokens} tokens \xB7 match score ${e.topScore})`}const ze=5;function lt(e){const t=e.filter(l=>!ee(l)&&te(l));if(!t.length)return"";const r=t.filter(l=>{const c=String(l.topic??"");return!(/^auto:/.test(c)||re(c))}),n=[...r.length?r:t].sort((l,c)=>(Number(c.recall_count)||0)-(Number(l.recall_count)||0)).slice(0,ze),s=n.map(M).join(`
5
5
  `),o=n.some(l=>(Number(l.recall_count)||0)>0),i=o?"Top by proven reuse":"Starter tips (not yet from your project)",a=o?z:z.replace("Stored notes from earlier sessions.","General starter notes, not yet from your project.");return`\u{1F9E0} Cachly Brain \u2014 ambient recall active (${t.length} lessons). ${i}:
6
6
  ${U(s,a)}
7
- (Relevant lessons for each task are auto-injected per prompt. ~${w(s)} tokens.)`}function it(e,t){return t?JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:t}}):""}function ze(e,t){return e.map((r,n)=>({x:r,rang:n,gezeigt:t.includes(r.lektion)})).filter(({rang:r,gezeigt:n})=>r<ue||n).map(({x:r,rang:n,gezeigt:s})=>({thema:String(r.lektion.topic??""),rang:n,punkte:Math.round(r.punkte*1e3)/1e3,belege:r.belege,leser:typeof r.leser=="number"&&Number.isFinite(r.leser)?Math.round(r.leser*1e3)/1e3:null,gezeigt:s}))}async function lt(e,t,{nebenlauf:r,abrufMs:n,leser:s=!0,session:o=null,protokoll:i=!0,ereignis:a="UserPromptSubmit",editor:l="",lernen:c=!0,fetchFn:m}={}){const{lessons:u,quelle:d}=await Re(t,{nebenlauf:r,abrufMs:n,fetchFn:m}),h=me(),E=c&&h.aktiv&&a==="UserPromptSubmit"&&!!t.instanceId,f=E?fe({instanceId:t.instanceId,sitzung:o,prompt:e,zaehlung:he(t.instanceId),einstellungen:h}):pe,x=O[f.arm]??O[0],g=await Y(e,u,t,{minBelege:ce,tiefe:s?K:0,zeitlimitMs:I,fetchFn:m}),p={...L(g.sortiert.filter(Z=>Z.belege>=x.minBelege),x.topK,600),leser:g.leser,leserMs:g.leserMs},N=f.kontrolle?"":Be(p);if(E&&g.sortiert.length>0&&ge(t.instanceId,o,Ee({sitzung:_e(o),zug:be(e),ereignis:a,editor:l,arm:f.arm,kontrolle:f.kontrolle,erkundet:f.erkundet,ausgewaehlt:p.lessons.length,kandidatenZahl:g.sortiert.length,belege:p.belege,topScore:p.topScore,leser:p.leser,leserMs:p.leserMs,quelle:d,bestand:u.length,kandidaten:ze(g.sortiert,p.lessons)})),i)try{V(Me,JSON.stringify({at:Date.now(),session:o,prompt_tokens:w(e),injected_tokens:N?p.tokens:0,matches:N?p.lessons.length:0,arm:f.arm,kontrolle:f.kontrolle,ausgewaehlt:p.lessons.length,top_score:p.topScore,belege:p.belege,leser:p.leser,leser_ms:p.leserMs,quelle:d,bestand:u.length})+`
8
- `)}catch{}return{kontext:N,auswahl:p,quelle:d,bestand:u.length,entscheidung:f}}export{D as ABRUF_TIMEOUT_MS,J as ANZEIGE_ZEICHEN,mt as ARME,ye as BESTAND_TTL_JUNG_MS,Ie as BESTAND_TTL_KLEIN_MS,Se as BESTAND_TTL_MS,Ae as JUNG_ABRUF_MS,P as JUNG_FENSTER_MS,Ne as KLEIN_LEKTIONEN,I as LESER_HOOK_ZEITLIMIT_MS,we as LESER_MAX_ZEICHEN,K as LESER_TIEFE,Me as NETZ_PROTOKOLL,Ue as SITZUNG_TOP_N,pt as belohnungMelden,ve as bestandFrist,q as bestandPfad,Ce as ergaenzeUmVorab,w as estimateTokens,Re as holeBestand,it as hookAusgabe,ht as lernEinstellungen,ft as lernenAuffrischen,G as leserAnfrageApi,nt as leserPunkteApi,$e as leserText,H as mischeMitLeser,lt as promptEinblendung,Be as promptKontext,M as renderLesson,et as resolveConfig,tt as schreibeVorabBestand,rt as selectRelevant,st as selectRelevantMitLeser,Le as sicherungsPfad,ot as sitzungsKontext,je as starteNebenlauf};
7
+ (Relevant lessons for each task are auto-injected per prompt. ~${w(s)} tokens.)`}function at(e,t){return t?JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:t}}):""}function He(e,t){return e.map((r,n)=>({x:r,rang:n,gezeigt:t.includes(r.lektion)})).filter(({rang:r,gezeigt:n})=>r<pe||n).map(({x:r,rang:n,gezeigt:s})=>({thema:String(r.lektion.topic??""),rang:n,punkte:Math.round(r.punkte*1e3)/1e3,belege:r.belege,leser:typeof r.leser=="number"&&Number.isFinite(r.leser)?Math.round(r.leser*1e3)/1e3:null,gezeigt:s}))}async function ct(e,t,{nebenlauf:r,abrufMs:n,leser:s=!0,session:o=null,protokoll:i=!0,ereignis:a="UserPromptSubmit",editor:l="",lernen:c=!0,fetchFn:m}={}){const{lessons:u,quelle:d}=await $e(t,{nebenlauf:r,abrufMs:n,fetchFn:m}),h=de(),E=c&&h.aktiv&&a==="UserPromptSubmit"&&!!t.instanceId,f=E?he({instanceId:t.instanceId,sitzung:o,prompt:e,zaehlung:me(t.instanceId),einstellungen:h}):fe,x=O[f.arm]??O[0],g=await Y(e,u,t,{minBelege:ue,tiefe:s?K:0,zeitlimitMs:I,fetchFn:m}),p={...L(g.sortiert.filter(Z=>Z.belege>=x.minBelege),x.topK,600),leser:g.leser,leserMs:g.leserMs},N=f.kontrolle?"":Ue(p);if(E&&g.sortiert.length>0&&Ee(t.instanceId,o,_e({sitzung:be(o),zug:Se(e),ereignis:a,editor:l,arm:f.arm,kontrolle:f.kontrolle,erkundet:f.erkundet,ausgewaehlt:p.lessons.length,kandidatenZahl:g.sortiert.length,belege:p.belege,topScore:p.topScore,leser:p.leser,leserMs:p.leserMs,quelle:d,bestand:u.length,kandidaten:He(g.sortiert,p.lessons)})),i)try{V(Le,JSON.stringify({at:Date.now(),session:o,prompt_tokens:w(e),injected_tokens:N?p.tokens:0,matches:N?p.lessons.length:0,arm:f.arm,kontrolle:f.kontrolle,ausgewaehlt:p.lessons.length,top_score:p.topScore,belege:p.belege,leser:p.leser,leser_ms:p.leserMs,quelle:d,bestand:u.length})+`
8
+ `)}catch{}return{kontext:N,auswahl:p,quelle:d,bestand:u.length,entscheidung:f}}export{D as ABRUF_TIMEOUT_MS,J as ANZEIGE_ZEICHEN,gt as ARME,Ae as BESTAND_TTL_JUNG_MS,ve as BESTAND_TTL_KLEIN_MS,ye as BESTAND_TTL_MS,Ne as JUNG_ABRUF_MS,P as JUNG_FENSTER_MS,Ie as KLEIN_LEKTIONEN,I as LESER_HOOK_ZEITLIMIT_MS,Me as LESER_MAX_ZEICHEN,K as LESER_TIEFE,Le as NETZ_PROTOKOLL,ze as SITZUNG_TOP_N,ht as belohnungMelden,ke as bestandFrist,q as bestandPfad,je as ergaenzeUmVorab,w as estimateTokens,$e as holeBestand,at as hookAusgabe,dt as lernEinstellungen,mt as lernenAuffrischen,G as leserAnfrageApi,ot as leserPunkteApi,Be as leserText,H as mischeMitLeser,ct as promptEinblendung,Ue as promptKontext,M as renderLesson,rt as resolveConfig,nt as schreibeVorabBestand,st as selectRelevant,it as selectRelevantMitLeser,xe as sicherungsPfad,lt as sitzungsKontext,Re as starteNebenlauf};
@@ -1,14 +1,14 @@
1
- import{ckgSlug as L}from"../ckg.js";import{safeJsonParse as x,darfHeraus as N}from"../utils.js";import{ersparteMinuten as F,zaehltAlsErsparnis as K}from"../wertbeitrag.js";import{findePaare as O}from"../zulassung-und-urteil.js";import{Vektorbestand as H}from"../bedeutung.js";import{doppelPaare as U}from"../doppel-kandidat.js";import{DOPPEL_SCHWELLE as W}from"../rangfolge-stellschrauben.js";import{sofortAntwortNeuesBrain as z}from"../leeres-brain.js";import{fuerWeitergabe as G}from"../schreibtor.js";import{kappeAnfrage as V,trefferIstStark as q}from"../pflichtfelder.js";function B(M){return N(M)&&!M.group}const ae=new Set(["memory_consolidate","brain_diff","causal_trace","knowledge_decay","autopilot"]);async function ie(M,D,R,P){switch(M){case"memory_consolidate":{const{instance_id:d,dry_run:_=!1,stale_days:y=90}=D,m=await R(d),f=Date.now(),k=y*86400*1e3;let c=0;const u=[];do{const[t,e]=await m.scan(c,"MATCH","cachly:lesson:best:*","COUNT",200);c=parseInt(t),u.push(...e)}while(c!==0);if(u.length===0)return"\u{1F9E0} **Brain is empty** \u2014 no lessons to consolidate yet. Use `learn_from_attempts` after your next bug fix.";const l=new Map;for(const t of u){const e=await m.get(t);if(!e)continue;const o=x(e,null);o&&l.set(t,o)}const g=new H(0);await g.aktualisiere(m).catch(()=>{});const w=U([...l.values()].flatMap(t=>{const e=g.rohvektor(t.topic);return e?[{lektion:t,vektor:e}]:[]})),$=[...l.values()],b=O($),p=b.filter(t=>t.beziehung==="widerspruch"),S=b.filter(t=>t.beziehung==="ersetzung"),a=[],n=new Map;for(const[t,e]of l){const o=n.get(e.topic)??[];o.push(t),n.set(e.topic,o)}for(const[t,e]of n)new Set(e.map(i=>l.get(i)?.outcome)).size>1&&a.push({topic:t,keys:e});const s=[];for(const[t,e]of l){const o=f-new Date(e.ts).getTime(),i=e.recall_count??0;o>k&&i===0&&s.push(t)}const r=0;if(!_)for(const t of s)await m.expire(t,86400*30);return[`\u{1F52C} **Memory Consolidation Report** ${_?"(dry run \u2014 no changes made)":"\u2705 Applied"}`,"",`\u{1F4CA} **Before:** ${u.length} lessons`,"",`\u{1F501} **Contradictions \u2014 exact topic match (old rule):** ${a.length}`,`\u{1F50E} **Same subject, admitted for judgement:** ${b.length} \u2192 contradiction ${p.length} \xB7 supersession ${S.length}`,...p.slice(0,5).map(t=>` \u2192 \`${t.a.topic}\` vs \`${t.b.topic}\` (${t.naehe.toFixed(2)}): ${t.grund}`),p.length>5?` \u2026 and ${p.length-5} more`:"",...S.slice(0,3).map(t=>` \u21BB \`${t.a.topic}\` \u2192 \`${t.b.topic}\`: ${t.grund}`),...a.slice(0,5).map(t=>` \u2192 \`${t.topic}\`: ${t.keys.length} conflicting entries (kept: success)`),a.length>5?` \u2026 and ${a.length-5} more`:"","",`\u267B\uFE0F **Possible duplicates \u2014 same meaning, different topic (cosine \u2265 ${W.toFixed(2)}, never merged):** ${w.length}`+(g.groesse===0?" (no vectors in this Brain, so nothing could be compared)":""),...w.slice(0,5).map(t=>` \u2192 \`${t.neu}\` \u2248 \`${t.alt}\` (${t.naehe.toFixed(2)})`),w.length>5?` \u2026 and ${w.length-5} more`:"",w.length>0?' If the newer one replaces the older, pass `ersetzt="<older topic>"` on its next `learn_from_attempts`.':"","",`\u{1F570}\uFE0F **Stale entries (${y}d, 0 recalls):** ${s.length}`+(s.length>0&&!_?" \u2192 set to expire in 30 days":""),"",`\u{1F4CA} **After:** ${u.length-r} lessons`,"",_?"\u{1F4A1} Re-run without dry_run=true to apply changes.":'\u2728 Brain consolidated. Run `brain_diff(since="1h")` to see the delta.'].filter(t=>t!=="").join(`
2
- `)}case"brain_diff":{const{instance_id:d,since:_="7d",format:y="summary"}=D,m=await R(d);let f;const k=_.match(/^(\d+)([dhm])$/);if(k){const e=parseInt(k[1]),o=k[2],i=o==="d"?864e5:o==="h"?36e5:6e4;f=Date.now()-e*i}else f=new Date(_).getTime()||Date.now()-7*864e5;let c=0;const u=[];do{const[e,o]=await m.scan(c,"MATCH","cachly:lesson:best:*","COUNT",200);c=parseInt(e),u.push(...o)}while(c!==0);const l=[],g=[],w=[],$=u.length;for(const e of u){const o=await m.get(e);if(o){const i=x(o,null);if(!i)continue;if(new Date(i.ts).getTime()>=f){const T=`cachly:lesson:history:${i.topic}`;await m.llen(T)<=1?l.push(i):g.push(i)}(i.recall_count??0)>0&&w.push(i)}}const p=[`\u{1F4CA} **Brain Diff** \u2014 ${k?`last ${_}`:new Date(f).toLocaleDateString("de-DE")}`,"",`Total lessons in brain: **${$}**`,"",`\u2705 **New** (${l.length}):`,...l.slice(0,y==="detailed"?20:5).map(e=>` + \`${e.topic}\` \u2014 ${e.outcome} ${e.severity==="critical"?"\u{1F534}":e.severity==="major"?"\u{1F7E0}":"\u{1F7E2}"}`),l.length>5&&y==="summary"?` \u2026 and ${l.length-5} more`:"","",`\u{1F504} **Updated** (${g.length}):`,...g.slice(0,y==="detailed"?20:5).map(e=>` ~ \`${e.topic}\` \u2014 now: ${e.outcome}`),g.length>5&&y==="summary"?` \u2026 and ${g.length-5} more`:"","",`\u{1F50D} **Active** (recalled at least once): ${w.length}`,""].filter(e=>e!==""),S=[],a=m.scanStream({match:"cachly:ckg:node:resolution-*",count:100});await new Promise((e,o)=>{a.on("data",i=>S.push(...i)),a.on("end",e),a.on("error",o)});const n=[];for(const e of S){const o=await m.get(e);if(o){const i=x(o,null);i?.ts&&new Date(i.ts).getTime()>=f&&n.push({topic:i.topic??e,resolution:i.resolution??"unknown",ts:i.ts})}}if(n.length>0){p.push(`\u{1F5F3}\uFE0F **MADC Resolutions** (${n.length} contested beliefs resolved):`);for(const e of n.slice(0,5)){const o=e.resolution==="unanimous_success"?"\u2705":e.resolution==="unanimous_failure"?"\u274C":"\u26A0\uFE0F";p.push(` ${o} \`${e.topic}\` \u2192 ${e.resolution}`)}p.push("")}const s=new Set(g.concat(w).map(e=>e.topic.split(":")[0])),r=[...new Set(l.map(e=>e.topic.split(":")[0]))].filter(e=>!s.has(e));r.length>0&&p.push(`\u{1F331} **New domains bootstrapped:** ${r.map(e=>`\`${e}\``).join(", ")}`,"");const t=(await m.lrange("cachly:fedbrain:federations",-20,-1)).map(e=>x(e,null)).filter(e=>e!==null&&new Date(e.transferred_at).getTime()>=f);if(t.length>0){p.push(`\u{1F9E0} **FedBrain transfers received (${t.length}):**`);for(const e of t.slice(0,3))p.push(` \u{1F4E5} domain \`${e.domain}\` from \`${e.source.slice(0,16)}\u2026\` \u2014 ${e.nodes} nodes, ${e.edges} edges`);p.push("")}return p.push("\u{1F4A1} Run `memory_consolidate` to merge duplicates \xB7 `knowledge_decay` to see confidence scores."),p.join(`
3
- `)}case"causal_trace":{const{instance_id:d,problem:_,max_depth:y=5,tags:m=[]}=D,f=V(_),k=await z(d,P,`\u{1F50D} **Causal Trace: "${f}"**
1
+ import{ckgSlug as L}from"../ckg.js";import{safeJsonParse as D,darfHeraus as O,istTeamweit as j}from"../utils.js";import{ersparteMinuten as F,zaehltAlsErsparnis as K}from"../wertbeitrag.js";import{findePaare as z}from"../zulassung-und-urteil.js";import{Vektorbestand as H}from"../bedeutung.js";import{doppelPaare as U}from"../doppel-kandidat.js";import{DOPPEL_SCHWELLE as W}from"../rangfolge-stellschrauben.js";import{sofortAntwortNeuesBrain as G}from"../leeres-brain.js";import{fuerWeitergabe as V}from"../schreibtor.js";import{kappeAnfrage as q,trefferIstStark as J}from"../pflichtfelder.js";import{namensPruefer as Y}from"./team.js";function N(B){return O(B)&&!B.group}const re=new Set(["memory_consolidate","brain_diff","causal_trace","knowledge_decay","autopilot"]);async function le(B,E,I,P){switch(B){case"memory_consolidate":{const{instance_id:u,dry_run:v=!1,stale_days:b=90}=E,g=await I(u),m=Date.now(),x=b*86400*1e3;let r=0;const p=[];do{const[t,f]=await g.scan(r,"MATCH","cachly:lesson:best:*","COUNT",200);r=parseInt(t),p.push(...f)}while(r!==0);if(p.length===0)return"\u{1F9E0} **Brain is empty** \u2014 no lessons to consolidate yet. Use `learn_from_attempts` after your next bug fix.";const l=new Map,$=new Set;for(const t of p){const f=await g.get(t);if(!f)continue;const S=D(f,null);if(S){l.set(t,S);const M=S.topic;j(S)||$.add(M)}}const _=(...t)=>t.every(f=>!$.has(f)),k=new H(0);await k.aktualisiere(g).catch(()=>{});const T=U([...l.values()].flatMap(t=>{const f=k.rohvektor(t.topic);return f?[{lektion:t,vektor:f}]:[]})),y=[...l.values()],C=z(y),a=C.filter(t=>t.beziehung==="widerspruch"),n=C.filter(t=>t.beziehung==="ersetzung"),o=[],c=new Map;for(const[t,f]of l){const S=c.get(f.topic)??[];S.push(t),c.set(f.topic,S)}for(const[t,f]of c)new Set(f.map(M=>l.get(M)?.outcome)).size>1&&o.push({topic:t,keys:f});const d=[];for(const[t,f]of l){const S=m-new Date(f.ts).getTime(),M=f.recall_count??0;S>x&&M===0&&d.push(t)}const w=0;if(!v)for(const t of d)await g.expire(t,86400*30);const h=a.filter(t=>_(t.a.topic,t.b.topic)),e=n.filter(t=>_(t.a.topic,t.b.topic)),i=o.filter(t=>_(t.topic)),s=T.filter(t=>_(t.neu,t.alt)),A=a.length-h.length+(n.length-e.length)+(o.length-i.length)+(T.length-s.length);return[`\u{1F52C} **Memory Consolidation Report** ${v?"(dry run \u2014 no changes made)":"\u2705 Applied"}`,"",`\u{1F4CA} **Before:** ${p.length} lessons`,"",`\u{1F501} **Contradictions \u2014 exact topic match (old rule):** ${o.length}`,`\u{1F50E} **Same subject, admitted for judgement:** ${C.length} \u2192 contradiction ${a.length} \xB7 supersession ${n.length}`,...h.slice(0,5).map(t=>` \u2192 \`${t.a.topic}\` vs \`${t.b.topic}\` (${t.naehe.toFixed(2)}): ${t.grund}`),h.length>5?` \u2026 and ${h.length-5} more`:"",...e.slice(0,3).map(t=>` \u21BB \`${t.a.topic}\` \u2192 \`${t.b.topic}\`: ${t.grund}`),...i.slice(0,5).map(t=>` \u2192 \`${t.topic}\`: ${t.keys.length} conflicting entries (kept: success)`),i.length>5?` \u2026 and ${i.length-5} more`:"","",`\u267B\uFE0F **Possible duplicates \u2014 same meaning, different topic (cosine \u2265 ${W.toFixed(2)}, never merged):** ${T.length}`+(k.groesse===0?" (no vectors in this Brain, so nothing could be compared)":""),...s.slice(0,5).map(t=>` \u2192 \`${t.neu}\` \u2248 \`${t.alt}\` (${t.naehe.toFixed(2)})`),s.length>5?` \u2026 and ${s.length-5} more`:"",s.length>0?' If the newer one replaces the older, pass `ersetzt="<older topic>"` on its next `learn_from_attempts`.':"",A>0?`\u{1F512} ${A} of the pairs above involve a private or group-only lesson and are counted, not named.`:"","",`\u{1F570}\uFE0F **Stale entries (${b}d, 0 recalls):** ${d.length}`+(d.length>0&&!v?" \u2192 set to expire in 30 days":""),"",`\u{1F4CA} **After:** ${p.length-w} lessons`,"",v?"\u{1F4A1} Re-run without dry_run=true to apply changes.":'\u2728 Brain consolidated. Run `brain_diff(since="1h")` to see the delta.'].filter(t=>t!=="").join(`
2
+ `)}case"brain_diff":{const{instance_id:u,since:v="7d",format:b="summary"}=E,g=await I(u);let m;const x=v.match(/^(\d+)([dhm])$/);if(x){const e=parseInt(x[1]),i=x[2],s=i==="d"?864e5:i==="h"?36e5:6e4;m=Date.now()-e*s}else m=new Date(v).getTime()||Date.now()-7*864e5;let r=0;const p=[];do{const[e,i]=await g.scan(r,"MATCH","cachly:lesson:best:*","COUNT",200);r=parseInt(e),p.push(...i)}while(r!==0);const l=[],$=[],_=[],k=p.length;for(const e of p){const i=await g.get(e);if(i){const s=D(i,null);if(!j(s))continue;if(new Date(s.ts).getTime()>=m){const R=`cachly:lesson:history:${s.topic}`;await g.llen(R)<=1?l.push(s):$.push(s)}(s.recall_count??0)>0&&_.push(s)}}const y=[`\u{1F4CA} **Brain Diff** \u2014 ${x?`last ${v}`:new Date(m).toLocaleDateString("de-DE")}`,"",`Total lessons in brain: **${k}**`,"",`\u2705 **New** (${l.length}):`,...l.slice(0,b==="detailed"?20:5).map(e=>` + \`${e.topic}\` \u2014 ${e.outcome} ${e.severity==="critical"?"\u{1F534}":e.severity==="major"?"\u{1F7E0}":"\u{1F7E2}"}`),l.length>5&&b==="summary"?` \u2026 and ${l.length-5} more`:"","",`\u{1F504} **Updated** (${$.length}):`,...$.slice(0,b==="detailed"?20:5).map(e=>` ~ \`${e.topic}\` \u2014 now: ${e.outcome}`),$.length>5&&b==="summary"?` \u2026 and ${$.length-5} more`:"","",`\u{1F50D} **Active** (recalled at least once): ${_.length}`,""].filter(e=>e!==""),C=[],a=g.scanStream({match:"cachly:ckg:node:resolution-*",count:100});await new Promise((e,i)=>{a.on("data",s=>C.push(...s)),a.on("end",e),a.on("error",i)});const n=[],o=Y(g);for(const e of C){const i=await g.get(e);if(i){const s=D(i,null);s?.ts&&new Date(s.ts).getTime()>=m&&(!s.topic||await o(s.topic))&&n.push({topic:s.topic??e,resolution:s.resolution??"unknown",ts:s.ts})}}if(n.length>0){y.push(`\u{1F5F3}\uFE0F **MADC Resolutions** (${n.length} contested beliefs resolved):`);for(const e of n.slice(0,5)){const i=e.resolution==="unanimous_success"?"\u2705":e.resolution==="unanimous_failure"?"\u274C":"\u26A0\uFE0F";y.push(` ${i} \`${e.topic}\` \u2192 ${e.resolution}`)}y.push("")}const c=new Set($.concat(_).map(e=>e.topic.split(":")[0])),d=[...new Set(l.map(e=>e.topic.split(":")[0]))].filter(e=>!c.has(e));d.length>0&&y.push(`\u{1F331} **New domains bootstrapped:** ${d.map(e=>`\`${e}\``).join(", ")}`,"");const h=(await g.lrange("cachly:fedbrain:federations",-20,-1)).map(e=>D(e,null)).filter(e=>e!==null&&new Date(e.transferred_at).getTime()>=m);if(h.length>0){y.push(`\u{1F9E0} **FedBrain transfers received (${h.length}):**`);for(const e of h.slice(0,3))y.push(` \u{1F4E5} domain \`${e.domain}\` from \`${e.source.slice(0,16)}\u2026\` \u2014 ${e.nodes} nodes, ${e.edges} edges`);y.push("")}return y.push("\u{1F4A1} Run `memory_consolidate` to merge duplicates \xB7 `knowledge_decay` to see confidence scores."),y.join(`
3
+ `)}case"causal_trace":{const{instance_id:u,problem:v,max_depth:b=5,tags:g=[]}=E,m=q(v),x=await G(u,P,`\u{1F50D} **Causal Trace: "${m}"**
4
4
 
5
- No matching lessons found in brain.`);if(k)return k;const c=await R(d),u=f.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(s=>s.length>2),l={critical:"\u{1F534}",major:"\u{1F7E0}",minor:"\u{1F7E1}"},g=[];try{for(const s of u.slice(0,4)){const r=await c.smembers(`cachly:ckg:idx:from:${L(s)}`),h=await c.smembers(`cachly:ckg:idx:to:${L(s)}`),t=[],e=c.scanStream({match:`cachly:ckg:node:*${s}*`,count:50});await new Promise((o,i)=>{e.on("data",v=>t.push(...v)),e.on("end",o),e.on("error",i)});for(const o of t.slice(0,10)){const i=await c.get(o);if(!i)continue;const v=x(i,null);if(!v)continue;const T=await c.smembers(`cachly:ckg:idx:from:${v.id}`);for(const C of T.slice(0,20)){const I=await c.get(C);if(!I)continue;const A=x(I,null);if(!A||A.edgeType!=="fixes"&&A.edgeType!=="requires")continue;const j=await c.get(`cachly:lesson:best:${A.from.replace(/-/g,":").replace(/^fix:/,"fix:")}`),E=j?x(j,null)??void 0:void 0;g.push({conceptId:v.id,edge:A,lesson:E&&B(E)?E:void 0})}}for(const o of[...r,...h].slice(0,20)){const i=await c.get(o);if(!i)continue;const v=x(i,null);if(!v)continue;const T=await c.get(`cachly:lesson:best:${v.from}`),C=T?x(T,null)??void 0:void 0;g.push({conceptId:v.from,edge:v,lesson:C&&B(C)?C:void 0})}}}catch{}const w=new Set,$=g.filter(s=>{const r=`${s.edge.from}:${s.edge.edgeType}:${s.edge.to}`;return w.has(r)?!1:(w.add(r),!0)}).sort((s,r)=>r.edge.confidence-s.edge.confidence).slice(0,y);let b=0;const p=[];do{const[s,r]=await c.scan(b,"MATCH","cachly:lesson:best:*","COUNT",200);b=parseInt(s),p.push(...r)}while(b!==0);const S=[];for(const s of p){const r=await c.get(s);if(r){const h=x(r,null);if(!h||!B(h)||m.length>0&&!(h.tags??[]).some(o=>m.includes(o)))continue;const t=[h.topic,h.what_failed??"",h.what_worked??"",h.context??""].join(" ").toLowerCase(),e=u.reduce((o,i)=>o+(t.includes(i)?1:0),0);e>0&&S.push({score:e,lesson:h,key:s})}}S.sort((s,r)=>r.score-s.score);const a=S.slice(0,y);if(a.length===0&&$.length===0)return[`\u{1F50D} **Causal Trace: "${f}"**`,"","No matching lessons found in brain.","","\u{1F4A1} After you solve this, call:","```","learn_from_attempts(",` instance_id = "${d}",`,` topic = "fix:${u[0]??"issue"}",`,' outcome = "success",',' what_worked = "...",',` what_failed = "${f}",`,")","```"].join(`
6
- `);const n=[`\u{1F50D} **Causal Trace: "${f}"**`,""];if($.length>0){n.push("### \u{1F578}\uFE0F CKG Graph (confidence-ranked)");for(const s of $){const r=Math.round(s.edge.confidence*100),h="\u2593".repeat(Math.round(r/10))+"\u2591".repeat(10-Math.round(r/10));n.push(` ${s.edge.from} **\u2192[${s.edge.edgeType}]\u2192** ${s.edge.to}`),n.push(` ${h} ${r}% confidence (${s.edge.successes}/${s.edge.trials} confirmed)`),s.lesson?.what_worked&&n.push(` \u2705 Fix: ${s.lesson.what_worked.slice(0,150)}`),n.push("")}}if(a.length>0){n.push($.length>0?`### \u{1F4DA} Text Search (${a.length} related lessons)`:`Found **${a.length}** related lessons. Reconstructed causal chain:`,"");const s=a.filter(t=>t.lesson.outcome!=="success"),r=a.filter(t=>t.lesson.outcome==="success");s.length>0&&(n.push("**Root causes & failure chain:**"),s.forEach((t,e)=>{const o=t.lesson,i=l[o.severity??"minor"]??"\u{1F7E1}";n.push(`${e===0?" Root:":" \u2192 :"} ${i} \`${o.topic}\``),o.what_failed&&n.push(` \u21B3 ${o.what_failed.slice(0,120)}`)}),n.push("")),r.length>0&&(n.push("**Solutions that worked before:**"),r.forEach((t,e)=>{const o=t.lesson,i=new Date(o.ts).toLocaleDateString("de-DE");n.push(` ${e+1}. \u2705 \`${o.topic}\` \u2014 ${i} \xB7 in ${o.recall_count??0} answers`),o.what_worked&&n.push(` ${o.what_worked.slice(0,200)}`)}),n.push(""));const h=r[0]?.lesson;if(h?.what_worked){const t=q(r[0].score,u);n.push(t?"**\u26A1 Most likely fix:**":`**Closest solution (weak match: ${r[0].score} of ${new Set(u).size} words \u2014 check that it fits before using it):**`),n.push("```"),n.push(h.what_worked.slice(0,500)),n.push("```"),n.push("");const e=K(h)?F(h,"trace"):0;e>0&&c.incrbyfloat(`cachly:stats:time_saved_mins:${d}`,e).catch(()=>{})}}return n.push(`\u{1F4A1} After applying: \`learn_from_attempts(topic="fix:${u[0]??"issue"}", outcome="success", ...)\``),$.length>0&&n.push(`\u{1F578}\uFE0F Explore graph: \`ckg_inspect(concept="${u[0]??"fix"}")\``),n.join(`
7
- `)}case"knowledge_decay":{let w=function(a){const n=Math.round(a/10);return"\u2588".repeat(n)+"\u2591".repeat(10-n)+` ${a}%`};const{instance_id:d,min_age_days:_=0,show_top:y=20}=D,m=await R(d),f=Date.now(),k=_*864e5;let c=0;const u=[];do{const[a,n]=await m.scan(c,"MATCH","cachly:lesson:best:*","COUNT",200);c=parseInt(a),u.push(...n)}while(c!==0);const l=[];for(const a of u){const n=await m.get(a);if(n){const s=x(n,null);if(!s)continue;const r=f-new Date(s.ts).getTime();if(r<k)continue;const h=Math.floor(r/864e5),t=s.recall_count??0,e=Math.max(0,h-7),o=Math.max(5,100-e),i=Math.min(50,t*5),v=s.outcome==="failure"?-20:0,T=Math.min(100,Math.max(0,o+i+v));l.push({topic:s.topic,confidence:T,age_days:h,recalls:t,outcome:s.outcome})}}l.sort((a,n)=>a.confidence-n.confidence);const g=l.slice(0,y),$=l.length>0?Math.round(l.reduce((a,n)=>a+n.confidence,0)/l.length):0,b=l.filter(a=>a.confidence<30).length,p=l.filter(a=>a.confidence>=70).length;return[`\u{1F9EA} **Knowledge Decay Report** \u2014 ${l.length} lessons`,"",`Average confidence: **${w($)}**`,`\u{1F534} Critical (<30%): ${b} \u{1F7E2} Healthy (\u226570%): ${p}`,"","Lowest confidence lessons (fix these first):","",...g.map((a,n)=>`${(n+1).toString().padStart(2)}. \`${a.topic}\`
8
- ${w(a.confidence)} \xB7 ${a.age_days}d old \xB7 ${a.recalls} recalls \xB7 ${a.outcome}`),"",l.length>y?`\u2026 and ${l.length-y} more lessons`:"","",b>0?`\u26A0\uFE0F ${b} lessons are critically stale. Validate them and re-run \`learn_from_attempts\` with updated findings.`:"\u2705 Brain confidence is healthy overall.","","\u{1F4A1} Run `memory_consolidate` to prune stale entries \xB7 `causal_trace` to find root causes."].filter(a=>a!=="").join(`
9
- `)}case"autopilot":{const{instance_id:d,editor:_="claude",project_name:y="this project",style:m="full"}=D,f=G({editor:String(_),project_name:String(y)},"the instruction file (CLAUDE.md)");if(!f.ok)return f.meldung;const k=(b,p)=>b.replace(/[\p{C}\s]+/gu," ").trim().slice(0,p),c=k(f.felder.editor,30)||"claude",u=k(f.felder.project_name,80)||"this project",l=`## Cachly AI Brain \u2014 Autopilot
5
+ No matching lessons found in brain.`);if(x)return x;const r=await I(u),p=m.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(o=>o.length>2),l={critical:"\u{1F534}",major:"\u{1F7E0}",minor:"\u{1F7E1}"},$=[];try{for(const o of p.slice(0,4)){const c=await r.smembers(`cachly:ckg:idx:from:${L(o)}`),d=await r.smembers(`cachly:ckg:idx:to:${L(o)}`),w=[],h=r.scanStream({match:`cachly:ckg:node:*${o}*`,count:50});await new Promise((e,i)=>{h.on("data",s=>w.push(...s)),h.on("end",e),h.on("error",i)});for(const e of w.slice(0,10)){const i=await r.get(e);if(!i)continue;const s=D(i,null);if(!s)continue;const A=await r.smembers(`cachly:ckg:idx:from:${s.id}`);for(const R of A.slice(0,20)){const t=await r.get(R);if(!t)continue;const f=D(t,null);if(!f||f.edgeType!=="fixes"&&f.edgeType!=="requires")continue;const S=await r.get(`cachly:lesson:best:${f.from.replace(/-/g,":").replace(/^fix:/,"fix:")}`),M=S?D(S,null)??void 0:void 0;$.push({conceptId:s.id,edge:f,lesson:M&&N(M)?M:void 0})}}for(const e of[...c,...d].slice(0,20)){const i=await r.get(e);if(!i)continue;const s=D(i,null);if(!s)continue;const A=await r.get(`cachly:lesson:best:${s.from}`),R=A?D(A,null)??void 0:void 0;$.push({conceptId:s.from,edge:s,lesson:R&&N(R)?R:void 0})}}}catch{}const _=new Set,k=$.filter(o=>{const c=`${o.edge.from}:${o.edge.edgeType}:${o.edge.to}`;return _.has(c)?!1:(_.add(c),!0)}).sort((o,c)=>c.edge.confidence-o.edge.confidence).slice(0,b);let T=0;const y=[];do{const[o,c]=await r.scan(T,"MATCH","cachly:lesson:best:*","COUNT",200);T=parseInt(o),y.push(...c)}while(T!==0);const C=[];for(const o of y){const c=await r.get(o);if(c){const d=D(c,null);if(!d||!N(d)||g.length>0&&!(d.tags??[]).some(e=>g.includes(e)))continue;const w=[d.topic,d.what_failed??"",d.what_worked??"",d.context??""].join(" ").toLowerCase(),h=p.reduce((e,i)=>e+(w.includes(i)?1:0),0);h>0&&C.push({score:h,lesson:d,key:o})}}C.sort((o,c)=>c.score-o.score);const a=C.slice(0,b);if(a.length===0&&k.length===0)return[`\u{1F50D} **Causal Trace: "${m}"**`,"","No matching lessons found in brain.","","\u{1F4A1} After you solve this, call:","```","learn_from_attempts(",` instance_id = "${u}",`,` topic = "fix:${p[0]??"issue"}",`,' outcome = "success",',' what_worked = "...",',` what_failed = "${m}",`,")","```"].join(`
6
+ `);const n=[`\u{1F50D} **Causal Trace: "${m}"**`,""];if(k.length>0){n.push("### \u{1F578}\uFE0F CKG Graph (confidence-ranked)");for(const o of k){const c=Math.round(o.edge.confidence*100),d="\u2593".repeat(Math.round(c/10))+"\u2591".repeat(10-Math.round(c/10));n.push(` ${o.edge.from} **\u2192[${o.edge.edgeType}]\u2192** ${o.edge.to}`),n.push(` ${d} ${c}% confidence (${o.edge.successes}/${o.edge.trials} confirmed)`),o.lesson?.what_worked&&n.push(` \u2705 Fix: ${o.lesson.what_worked.slice(0,150)}`),n.push("")}}if(a.length>0){n.push(k.length>0?`### \u{1F4DA} Text Search (${a.length} related lessons)`:`Found **${a.length}** related lessons. Reconstructed causal chain:`,"");const o=a.filter(w=>w.lesson.outcome!=="success"),c=a.filter(w=>w.lesson.outcome==="success");o.length>0&&(n.push("**Root causes & failure chain:**"),o.forEach((w,h)=>{const e=w.lesson,i=l[e.severity??"minor"]??"\u{1F7E1}";n.push(`${h===0?" Root:":" \u2192 :"} ${i} \`${e.topic}\``),e.what_failed&&n.push(` \u21B3 ${e.what_failed.slice(0,120)}`)}),n.push("")),c.length>0&&(n.push("**Solutions that worked before:**"),c.forEach((w,h)=>{const e=w.lesson,i=new Date(e.ts).toLocaleDateString("de-DE");n.push(` ${h+1}. \u2705 \`${e.topic}\` \u2014 ${i} \xB7 in ${e.recall_count??0} answers`),e.what_worked&&n.push(` ${e.what_worked.slice(0,200)}`)}),n.push(""));const d=c[0]?.lesson;if(d?.what_worked){const w=J(c[0].score,p);n.push(w?"**\u26A1 Most likely fix:**":`**Closest solution (weak match: ${c[0].score} of ${new Set(p).size} words \u2014 check that it fits before using it):**`),n.push("```"),n.push(d.what_worked.slice(0,500)),n.push("```"),n.push("");const h=K(d)?F(d,"trace"):0;h>0&&r.incrbyfloat(`cachly:stats:time_saved_mins:${u}`,h).catch(()=>{})}}return n.push(`\u{1F4A1} After applying: \`learn_from_attempts(topic="fix:${p[0]??"issue"}", outcome="success", ...)\``),k.length>0&&n.push(`\u{1F578}\uFE0F Explore graph: \`ckg_inspect(concept="${p[0]??"fix"}")\``),n.join(`
7
+ `)}case"knowledge_decay":{let _=function(a){const n=Math.round(a/10);return"\u2588".repeat(n)+"\u2591".repeat(10-n)+` ${a}%`};const{instance_id:u,min_age_days:v=0,show_top:b=20}=E,g=await I(u),m=Date.now(),x=v*864e5;let r=0;const p=[];do{const[a,n]=await g.scan(r,"MATCH","cachly:lesson:best:*","COUNT",200);r=parseInt(a),p.push(...n)}while(r!==0);const l=[];for(const a of p){const n=await g.get(a);if(n){const o=D(n,null);if(!j(o))continue;const c=m-new Date(o.ts).getTime();if(c<x)continue;const d=Math.floor(c/864e5),w=o.recall_count??0,h=Math.max(0,d-7),e=Math.max(5,100-h),i=Math.min(50,w*5),s=o.outcome==="failure"?-20:0,A=Math.min(100,Math.max(0,e+i+s));l.push({topic:o.topic,confidence:A,age_days:d,recalls:w,outcome:o.outcome})}}l.sort((a,n)=>a.confidence-n.confidence);const $=l.slice(0,b),k=l.length>0?Math.round(l.reduce((a,n)=>a+n.confidence,0)/l.length):0,T=l.filter(a=>a.confidence<30).length,y=l.filter(a=>a.confidence>=70).length;return[`\u{1F9EA} **Knowledge Decay Report** \u2014 ${l.length} lessons`,"",`Average confidence: **${_(k)}**`,`\u{1F534} Critical (<30%): ${T} \u{1F7E2} Healthy (\u226570%): ${y}`,"","Lowest confidence lessons (fix these first):","",...$.map((a,n)=>`${(n+1).toString().padStart(2)}. \`${a.topic}\`
8
+ ${_(a.confidence)} \xB7 ${a.age_days}d old \xB7 ${a.recalls} recalls \xB7 ${a.outcome}`),"",l.length>b?`\u2026 and ${l.length-b} more lessons`:"","",T>0?`\u26A0\uFE0F ${T} lessons are critically stale. Validate them and re-run \`learn_from_attempts\` with updated findings.`:"\u2705 Brain confidence is healthy overall.","","\u{1F4A1} Run `memory_consolidate` to prune stale entries \xB7 `causal_trace` to find root causes."].filter(a=>a!=="").join(`
9
+ `)}case"autopilot":{const{instance_id:u,editor:v="claude",project_name:b="this project",style:g="full"}=E,m=V({editor:String(v),project_name:String(b)},"the instruction file (CLAUDE.md)");if(!m.ok)return m.meldung;const x=(T,y)=>T.replace(/[\p{C}\s]+/gu," ").trim().slice(0,y),r=x(m.felder.editor,30)||"claude",p=x(m.felder.project_name,80)||"this project",l=`## Cachly AI Brain \u2014 Autopilot
10
10
 
11
- **Instance:** \`${d}\`
11
+ **Instance:** \`${u}\`
12
12
 
13
13
  > **Where your data goes:** these calls read/write *your own* Brain instance
14
14
  > (the ID above) \u2014 your infrastructure, EU-hosted, under your control. Nothing
@@ -19,12 +19,12 @@ No matching lessons found in brain.`);if(k)return k;const c=await R(d),u=f.toLow
19
19
  > Sessions are fully automatic. The Brain starts when you call any tool and saves a summary when you close.
20
20
 
21
21
  ### Brain hooks \u2014 run these automatically (safe to skip if a step doesn't apply):
22
- - **Window opens** \u2192 call \`session_start(instance_id="${d}", focus="<today's goal>")\`
23
- - **Bug fixed / deployed / discovered** \u2192 call \`learn_from_attempts(instance_id="${d}", topic="fix:<area>", outcome="success", what_worked="...")\`
24
- - **Window closes** \u2192 call \`session_end(instance_id="${d}", summary="...", files_changed=[...])\`
25
- `,g=`## Cachly AI Brain \u2014 Autopilot for ${u}
22
+ - **Window opens** \u2192 call \`session_start(instance_id="${u}", focus="<today's goal>")\`
23
+ - **Bug fixed / deployed / discovered** \u2192 call \`learn_from_attempts(instance_id="${u}", topic="fix:<area>", outcome="success", what_worked="...")\`
24
+ - **Window closes** \u2192 call \`session_end(instance_id="${u}", summary="...", files_changed=[...])\`
25
+ `,$=`## Cachly AI Brain \u2014 Autopilot for ${p}
26
26
 
27
- **Instance:** \`${d}\`
27
+ **Instance:** \`${u}\`
28
28
 
29
29
  > **What this is & where your data goes:** the calls below read and write to
30
30
  > *your own* Cachly Brain instance (the ID above) \u2014 your infrastructure,
@@ -42,7 +42,7 @@ No matching lessons found in brain.`);if(k)return k;const c=await R(d),u=f.toLow
42
42
  ### Rule 1 \u2014 Session Start (FIRST thing in every window)
43
43
  \`\`\`
44
44
  session_start(
45
- instance_id = "${d}",
45
+ instance_id = "${u}",
46
46
  focus = "<what you plan to work on today>",
47
47
  )
48
48
  \`\`\`
@@ -52,7 +52,7 @@ Returns: last session summary, handoff tasks, recent lessons, open failures.
52
52
  **After EVERY** bug fix, deployment, or technical discovery \u2014 call immediately:
53
53
  \`\`\`
54
54
  learn_from_attempts(
55
- instance_id = "${d}",
55
+ instance_id = "${u}",
56
56
  topic = "category:keyword",
57
57
  outcome = "success" | "failure" | "partial",
58
58
  what_worked = "exact command or approach",
@@ -72,7 +72,7 @@ learn_from_attempts(
72
72
  ### Rule 3 \u2014 Session End (LAST thing before closing)
73
73
  \`\`\`
74
74
  session_end(
75
- instance_id = "${d}",
75
+ instance_id = "${u}",
76
76
  summary = "What was accomplished (2-3 sentences)",
77
77
  files_changed = ["list", "of", "changed", "files"],
78
78
  lessons_learned = <number of learn_from_attempts calls>,
@@ -82,7 +82,7 @@ session_end(
82
82
  ### Rule 4 \u2014 Before any non-trivial task
83
83
  \`\`\`
84
84
  smart_recall(
85
- instance_id = "${d}",
85
+ instance_id = "${u}",
86
86
  query = "<describe what you are about to do>",
87
87
  )
88
88
  \`\`\`
@@ -93,13 +93,13 @@ smart_recall(
93
93
 
94
94
  | When | Call |
95
95
  |---|---|
96
- | Brain feeling cluttered | \`memory_consolidate(instance_id="${d}")\` |
97
- | Weekly review | \`brain_diff(instance_id="${d}", since="7d")\` |
98
- | Weird bug, no idea why | \`causal_trace(instance_id="${d}", problem="<symptom>")\` |
99
- | Before big refactor | \`knowledge_decay(instance_id="${d}")\` |
96
+ | Brain feeling cluttered | \`memory_consolidate(instance_id="${u}")\` |
97
+ | Weekly review | \`brain_diff(instance_id="${u}", since="7d")\` |
98
+ | Weird bug, no idea why | \`causal_trace(instance_id="${u}", problem="<symptom>")\` |
99
+ | Before big refactor | \`knowledge_decay(instance_id="${u}")\` |
100
100
 
101
101
  ---
102
102
 
103
103
  *Cachly v0.6 \xB7 Generated ${new Date().toISOString().slice(0,10)}*
104
- `,w=m==="minimal"?l:g,$=c==="copilot"?".github/copilot-instructions.md":c==="continue"?".continue/cachly-autopilot.md":"CLAUDE.md";return[`\u{1F916} **Autopilot instructions generated** for **${c==="all"?"all editors":c}**`,"",`**File:** \`${$}\` \u2014 create it, or APPEND to your existing one`,"","```markdown",w,"```","",`**How to apply** (\`>>\` appends \u2014 an existing ${$} keeps every line you wrote):`,"```bash",`cat >> ${$} << 'EOF'`,w,"EOF","```","",`\u2728 Once this file is in place, **${c==="copilot"?"GitHub Copilot":c==="continue"?"Continue.dev":"Claude/Cursor/Windsurf"}** will manage the Brain automatically \u2014 no manual calls needed, ever.`].join(`
105
- `)}default:return null}}export{ae as ADVANCED_TOOL_NAMES,ie as handleAdvancedTool};
104
+ `,_=g==="minimal"?l:$,k=r==="copilot"?".github/copilot-instructions.md":r==="continue"?".continue/cachly-autopilot.md":"CLAUDE.md";return[`\u{1F916} **Autopilot instructions generated** for **${r==="all"?"all editors":r}**`,"",`**File:** \`${k}\` \u2014 create it, or APPEND to your existing one`,"","```markdown",_,"```","",`**How to apply** (\`>>\` appends \u2014 an existing ${k} keeps every line you wrote):`,"```bash",`cat >> ${k} << 'EOF'`,_,"EOF","```","",`\u2728 Once this file is in place, **${r==="copilot"?"GitHub Copilot":r==="continue"?"Continue.dev":"Claude/Cursor/Windsurf"}** will manage the Brain automatically \u2014 no manual calls needed, ever.`].join(`
105
+ `)}default:return null}}export{re as ADVANCED_TOOL_NAMES,le as handleAdvancedTool};